//
//  M4LoanPrivacyViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/20.
//

import UIKit
import WebKit

class M4LoanPrivacyViewController: M4BaseViewController, WKNavigationDelegate {
    
    private var M4WebView: WKWebView!
    
    @IBOutlet weak var M4LoanPrivacyView: UIView!
    
    var productPara: [String : Any] = [:]
    
    var productID: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        M4NavTitle(M4Title: "Acuerdo de préstamo", M4NavTitleColor: .white)
        M4WebView = WKWebView(frame: .zero, configuration: M4WebConfig)
//        M4WebView = WKWebView.init(frame: CGRect(x: 15, y: 10, width: M4ScreenWidth, height: M4ScreenHeight-M4NavigationFullHeight()-M4SafeDistanceBottom()), configuration: M4WebConfig)
        M4LoanPrivacyView.addSubview(M4WebView)
        M4WebView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.bottom.equalToSuperview().offset(-10)
        }
        M4WebView.navigationDelegate = self
        M4WebView.scrollView.showsHorizontalScrollIndicator = false
        M4WebView.scrollView.showsVerticalScrollIndicator = false
        var M4WebUrl  = M4NetworkAPI.m4htmlPath.rawValue + "/asdasd?vcxoPPo=\(M4UserDataManager.m4UserShare.M4Token)&sesaPPOs=\(productID)"
        M4WebUrl = M4WebUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        var request = URLRequest.init(url: URL.init(string: M4WebUrl)!)
        request.cachePolicy = .reloadIgnoringCacheData
        
        
        let dataStore = WKWebsiteDataStore.default()
                dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), completionHandler: { (records) in
                    for record in records{
                        // 清除指定网站
                        //                        if record.displayName.contains("sina.com") {
                        WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {
                            //清除成功
                            print("清除成功\(record)")
                        })
//                    }
                    }
                })
        
        M4WebView.load(request)
    }
    
    lazy private var M4WebConfig: WKWebViewConfiguration = {
//        let userContent = WKUserContentController()
//        userContent.add(self, name: "toastMessage")
//        userContent.add(self, name: "backUpPage")
//        userContent.add(self, name: "Displayloading")
//        userContent.add(self, name: "hideloadding")
        let config = WKWebViewConfiguration()
//        config.selectionGranularity = .dynamic
        config.mediaTypesRequiringUserActionForPlayback = .all
        config.allowsInlineMediaPlayback = true
//        config.userContentController = userContent
        let preference = WKPreferences()
        preference.javaScriptCanOpenWindowsAutomatically = true
        config.preferences = preference
        return config
    }()
    

    @IBAction func M4LoanButtonClick(_ sender: UIButton) {
        M4LimitVerification().M4LimitDataAsk1 { arrayCount in
            sender.M4EventUnavailable = false
            if arrayCount.count > 0 {
                M4LimitVerification().M4_showAskAlert(arr: arrayCount) { _ in }
            }
            else {
                //检查/上传埋点，跳转提单页
                M4PublicNetwork.M4CheckNeedUpload { t in
                    if t == 1 {
                        if M4UserDataManager.M4HasShowUploadPage == false {
                            M4PublicNetwork.M4ShowUploadAlert { r in
                                self.M4UploadDataDone(r: r)
                            }
                        } else {
                            M4PublicNetwork.M4ShowUploadAlert { r in
                                self.M4UploadDataDone(r: r)
                            }
                        }
                    } else {
                        self.M4UploadDataDone(r: true)
                    }
                }
                
                
//                if M4UserDataManager.M4HasShowUploadPage == false {
//                    let uploadController = M4UploadController()
//                    uploadController.M4UploadResult = { issuccess in
//                        self.M4UploadDataDone(r: issuccess)
//                    }
//                    self.navigationController?.pushViewController(uploadController, animated: true)
//                } else {
//                    let loading = M4LoadingAlertView()
//                    loading.M4LoadingAlertShow()
//                    M4PublicNetwork.M4VerficationPointDataNet(false) { issuccess in
//                        loading.M4AlertViewHidden()
//                        self.M4UploadDataDone(r: issuccess)
//                    }
//                }
            }
        }
    }
    
    @IBAction func M4LoanPrivacyCloseClick(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
        sender.M4EventUnavailable = false
    }
    
    func M4UploadDataDone(r: Bool) {
        if r {
            let loading = M4LoadingAlertView()
            loading.M4LoadingAlertShow()
            M4PublicNetwork.M4SubmitLoanNet(false, paramnet: self.productPara) { issuccess, loanId in
                loading.M4AlertViewHidden()
                if issuccess {
                    let page = M4LoanResultViewController()
                    page.M4LoanId = loanId
                    self.navigationController?.pushViewController(page, animated: true)
                }
            }
        }
    }

}
